package utils

import (
	"crypto/md5"
	"encoding/hex"
	"github.com/gin-gonic/gin"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

// RandomNum 生成不会重复的字符串（根据时间戳和随机数生成数据）
func RandomNum() string {
	//根据时间戳生成随机数
	res := rand.Intn(time.Now().Second())
	h := md5.New()
	h.Write([]byte(strconv.Itoa(res + time.Now().Second())))
	resMd5 := hex.EncodeToString(h.Sum(nil))
	return resMd5
}

// Static 给静态文件添加content-type
func Static() func(c *gin.Context) {
	return func(c *gin.Context) {
		path := c.Request.URL.Path
		suffix := strings.Split(path, ".")
		if len(suffix) > 1 {
			switch suffix[1] {
			case "css":
				c.Writer.Header().Set("content-type", "text/css; charset=utf-8")
				c.Next()
			case "js":
				c.Writer.Header().Set("content-type", "application/javascript")
				c.Next()
			default:
				c.Next()
			}
		} else {
			c.Next()
		}
	}
}
